#include "TcpClient.h"

// 构造函数
TcpClient::TcpClient(const char* ssid, const char* password, const char* serverHost, uint16_t serverPort) {
  _ssid = ssid;
  _password = password;
  _serverHost = serverHost;
  _serverPort = serverPort;
}

// 初始化
void TcpClient::begin() {
  Serial.println("=== TCP Client 初始化 ===");
  if (_connectWiFi()) {
    Serial.print("ESP32 IP 地址：");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("WiFi 初始化失败，请检查配置！");
  }
}

// 主循环
void TcpClient::loop() {
  // 检查WiFi连接
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("\nWiFi 已断开，尝试重连...");
    _connectWiFi();
    delay(1000);
    return;
  }

  // 检查服务器连接
  if (!_client.connected()) {
    unsigned long currentTime = millis();
    if (currentTime - _lastAttemptTime >= _reconnectInterval) {
      _lastAttemptTime = currentTime;
      Serial.print("\n尝试连接服务器 ");
      Serial.print(_serverHost);
      Serial.print(":");
      Serial.println(_serverPort);

      if (_connectServer()) {
        Serial.println("服务器连接成功！");
        _isConnected = true;
      }
    }
  } else {
    // 检查服务器响应
    if (_client.available()) {
      _readResponse();
    }
  }
}

// 连接WiFi
bool TcpClient::_connectWiFi() {
  Serial.print("正在连接 WiFi (");
  Serial.print(_ssid);
  Serial.print(")...");

  WiFi.begin(_ssid, _password);
  int retry = 0;
  while (WiFi.status() != WL_CONNECTED && retry < 20) {
    delay(500);
    Serial.print(".");
    retry++;
  }

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("\nWiFi 连接成功！");
    return true;
  } else {
    Serial.println("\nWiFi 连接失败（检查 SSID/密码）");
    return false;
  }
}

// 连接服务器
bool TcpClient::_connectServer() {
  _client.connect(_serverHost, _serverPort);
  delay(200);

  return _client.connected();
}

// 发送消息
bool TcpClient::_sendMessage(const String& message) {
  if (!_client.connected()) {
    Serial.println("发送失败：未连接到服务器");
    return false;
  }

  _client.println(message);
  Serial.print("已发送消息：");
  Serial.println(message);
  return true;
}

// 读取响应
String TcpClient::_readResponse() {
  String response = "";
  unsigned long timeout = millis() + 5000;

  while (_client.available() == 0 && millis() < timeout) {
    delay(10);
  }

  while (_client.available() > 0) {
    response += (char)_client.read();
    delay(5);
  }

  if (response.length() > 0) {
    Serial.print("服务器响应：");
    Serial.println(response);
  } else {
    Serial.println("未收到服务器响应（或超时）");
  }
  return response;
}

// 发送单个电位器数据
bool TcpClient::sendPotentiometerData(uint8_t channel, uint16_t value) {
  String data = "POT," + String(channel) + "," + String(value);
  return _sendMessage(data);
}

// 发送多个电位器数据
bool TcpClient::sendMultiplePotentiometerData(uint16_t values[16]) {
  String data = "POTS";
  for (uint8_t i = 0; i < 16; i++) {
    data += "," + String(values[i]);
  }
  return _sendMessage(data);
}
